<!-- 营销活动列表 -->
<template>
  <page-header-wrapper>
    <a-card v-show="!vdata.currentApplyPage.component" class="table-card">
      <GzSearchForm :searchFunc="searchFunc" :resetFunc="() => { searchData = {};gzThreeRef.clear(); }" searchConditionNum="6">
        <a-form-item class="table-search-item" label="归属机构">
          <GzTreeSelect ref="gzThreeRef" v-model:value="searchData['agentNo']" :isNeedDefault="false" />
        </a-form-item>
        <a-form-item class="table-search-item" label="活动编号">
          <a-input v-model:value="searchData['activityNo']" :placeholder="'活动编号'" />
        </a-form-item>
        <a-form-item class="table-search-item" label="活动名称">
          <a-input v-model:value="searchData['activityName']" :placeholder="'活动名称'" />
        </a-form-item>
        <a-form-item label="活动状态" class="table-search-item">
          <a-select v-model:value="searchData['state']" placeholder="活动状态">
            <a-select-option value="">全部</a-select-option>
            <a-select-option :value="0">草稿</a-select-option>
            <a-select-option :value="1">审批中</a-select-option>
            <a-select-option :value="2">通过</a-select-option>
            <a-select-option :value="3">未通过</a-select-option>
            <a-select-option :value="4">上线</a-select-option>
            <a-select-option :value="5">下线</a-select-option>
            <a-select-option :value="6">已结束</a-select-option>
            <a-select-option :value="7">垫资方参数已回执</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item class="table-search-item" label="开始时间">
          <a-date-picker
            v-model:value="searchData['startTime']"
            show-time
            valueFormat="YYYY-MM-DD HH:mm:ss"
            :placeholder="'活动开始时间'"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item class="table-search-item" label="结束时间">
          <a-date-picker
            v-model:value="searchData['endTime']"
            show-time
            valueFormat="YYYY-MM-DD HH:mm:ss"
            :placeholder="'活动结束时间'"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item label="活动类型" class="table-search-item">
          <a-select
            v-model:value="searchData['activityTypeNo']"
            placeholder="活动类型"
            :options="activityType"
            :field-names="{
              label: 'activityTypeName',
              value: 'activityTypeNo',
            }"
          />
        </a-form-item>
        <a-form-item label="商圈" class="table-search-item">
          <a-select
            v-model:value="searchData['groupId']"
            placeholder="商圈"
            :options="groupList"
            :field-names="{ label: 'groupName', value: 'groupId' }"
          />
        </a-form-item>
      </GzSearchForm>

      <!-- 列表渲染 -->
      <GzTable
        ref="infoTableRef"
        :init-data="true"
        :req-table-data-func="reqTableDataFunc"
        :table-columns="tableColumns"
        :search-data="searchData"
        :pageSize="5"
      >
        <template #topBtnSlot>
          <a-button v-if="$access('ENT_ACTIVITY_LIST_ADD')" type="primary" @click="switchApplyPage({ page: 'activityCreateSelectActivityTemplate', params: { activityTemplateCode: activityTemplateCode } })">
            <plus-outlined />新建活动
          </a-button>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="$access('ENT_ACTIVITY_LIST_INFO_VIEW') && column.key === 'activityName'">
            <b><a @click="activityEdit(record,true)">{{ record.activityName }}</a></b>
          </template>
          <tempalte v-if="column.key === 'activityImg'">
            <template v-if="record.activityImg">
              <a-image :src="record.activityImg" />
            </template>
            <template v-else-if="record.templateImg">
              <a-image :src="record.templateImg" />
            </template>
            <template v-else>
              <img src="@/assets/svg/default-img.svg" alt="">
            </template>
          </tempalte>
          <template v-if="column.key === 'state'">
            <a-badge v-if="record.state == 0" status="default" text="草稿" />
            <a-badge v-if="record.state == 1" status="processing" text="审核中" />
            <a-badge v-if="record.state == 2" status="success" text="通过" />
            <a-badge v-if="record.state == 3" status="error" text="未通过" />
            <a-badge v-if="record.state == 4" status="success" text="上线" />
            <a-badge v-if="record.state == 5" status="warning" text="下线" />
            <a-badge v-if="record.state == 6" status="default" text="已结束" />
            <a-badge v-if="record.state == 7" status="success" text="垫资方参数已回执" />
            <a-badge v-if="record.state == 8" status="error" text="异常活动" />
            <a-popover v-if="record.state === 3 || record.state === 8" placement="top">
              <template #content>
                <span>{{ record.errorInfo }}</span>
              </template>
              <question-circle-outlined />
            </a-popover>
          </template>
          <!-- 如果提前曝光时间为空，则同活动开始时间 -->
          <template v-if="column.key === 'exposureTime'">
            <template v-if="!record.exposureTime">
              {{ record.startTime ? record.startTime :'--' }}
            </template>
            <template v-else>
              {{ record.exposureTime }}
            </template>
          </template>

          <template v-if="column.key === 'operation'"> 
            <!-- 操作列插槽 -->
            <GzTableColumns>
              <a-button v-if="$access('ENT_ACTIVITY_LIST_INFO_PLATE') && (record.state === 4 || record.state === 5 ||record.state === 6) && record.activityTemplateNo != 'ACTE015' && record.activityTemplateNo != 'ACTE016' && record.activityTemplateNo != 'ACTE020' && record.activityTemplateNo != 'ACTE021'" type="link" @click="onStatistics(record)">基础数据报表</a-button>
              <a-button v-if="$access('ENT_ACTIVITY_LIST_INFO_STATS') && (record.state === 4 || record.state === 5) && record.activityTemplateNo == 'ACTE017'" type="link" @click="onStatistical(record)">统计看板</a-button>
              <a-button v-if="$access('ENT_ACTIVITY_LIST_INFO_VIEW')" type="link" @click="activityEdit(record,true)">查看</a-button>
              <a-button v-if="$access('ENT_ACTIVITY_LIST_INFO_REVOKE') && record.operable &&record.state==1" type="link" @click="withdrawReview(record)">撤回审核</a-button>
              <a-button v-if="$access('ENT_ACTIVITY_LIST_INFO_ADD_QR') && record.operable && (record.state === 4 || record.state === 5) && record.activityTemplateNo == 'ACTE004'" type="link" @click="generateCodeRef.show(record.activityId,record.agentNo)">生成券码</a-button>
              <a-button v-if="$access('ENT_ACTIVITY_LIST_INFO_EXPT_QR') && record.operable && (record.state === 4 || record.state === 5) && record.activityTemplateNo == 'ACTE004'" type="link" @click="onQrcodeExport(record.activityId,record)">导出券码</a-button>
              <a-button v-if="$access('ENT_ACTIVITY_LIST_INFO_EDIT') && record.operable && (record.state === 2 || record.state === 5 || record.state === 7)" type="link" @click="activityState(4, record.activityId)">上线</a-button>
              <a-button v-if="$access('ENT_ACTIVITY_LIST_INFO_EDIT') && record.operable && record.state === 4" type="link" @click="activityState(5, record.activityId)">下线</a-button>
              <a-button v-if="$access('ENT_ACTIVITY_LIST_INFO_EDIT') && record.operable && (record.state === 0 || record.state === 3)" type="link" @click="activityEdit(record)">修改</a-button>
              <a-button v-if="$access('ENT_ACTIVITY_LIST_INFO_IMPT_USER') && record.operable && record.activityTemplateNo =='ACTE022'&& record.state == 4" type="link" @click="() => exportListRef.show(record)">导入名单</a-button>
              <a-button v-if="$access('ENT_ACTIVITY_LIST_INFO_IMPT_USER') && record.operable && record.activityTemplateNo =='ACTE023'&& record.state == 4" type="link" @click="() => exportScoreListRef.show(record)">导入名单</a-button>
              <!-- 除导出报表外，其他操作按钮都需要判断是否可操作 -- 导出报表迁移至活动看板内 20250728 -->
              <!-- <a-button v-if="$access('ENT_ACTIVITY_LIST_INFO_EXPT_STMT') && (record.state === 4 || record.state === 5 || record.state === 6)" type="link" @click="exportTable(record.activityId,record.activityName)">导出报表</a-button> -->
              <a-button v-if="$access('ENT_ACTIVITY_LIST_INFO_DEL') && record.operable && record.state === 0" type="link" danger @click="activityDelete(record)">删除</a-button>
            </GzTableColumns>
          </template>
        </template>
      </GzTable>
    </a-card>

    <!-- 定义组件分为： 活动看板 创建活动 -->
    <a-card>
      <component :is="vdata.currentApplyPage.component" ref="applyPageComponentRef" :activityDetail="vdata.activityDetail" @switchApplyPage="switchApplyPage" />
    </a-card>
    <!-- 统计页面组件  -->
    <!-- <ActivityStatistics v-if="vdata.page.component" :activityDetail="vdata.activityDetail" @switchApplyPage="switchApplyPage" /> -->
    <!-- 生成二维码 -->
    <GenerateCode ref="generateCodeRef" />
    <!-- 导入名单 -->
    <exportList ref="exportListRef" />
    <!-- 导入名单带福分 -->
    <exportScoreList ref="exportScoreListRef" />
  </page-header-wrapper>
</template>

<script lang="ts" setup>
import ActivityStatistics from '@/views/activity/activityStatistics/ActivityStatistics.vue'
import StatisticalDashboard from '@/views/activity/statisticalDashboard/statisticalDashboard.vue'
import ActivityCreateEntry from '@/views/activity/activityList/components/ActivityCreateEntry.vue'
import ActivityCreateSelectActivityTemplate from '@/views/activity/activityList/components/ActivityCreateSelectActivityTemplate.vue'
import GenerateCode from '@/views/activity/activityList/GenerateCode.vue'
import exportList from '@/views/activity/activityList/exportList.vue'
import exportScoreList from './exportScoreList.vue'
import { req, API_URL_ACTIVITY_TEMPLATE, API_URL_ACTIVITY_TYPE,  $exportZip,$activityState,  $exportExcel, API_URL_EXPORT_ACTIVITY_AWARD } from '@/api/manage'
import { $getContributorList }from '@/api/awardMange/coupon/index'
import { $activityList, $activityDelete,$withdrawReview } from '@/api/activityManage/activityList/index'
import fileDownload from 'js-file-download'
import { ref, reactive, getCurrentInstance, nextTick, provide, computed } from 'vue'
import { useRoute } from 'vue-router'
import { watch } from 'vue'
 const route = useRoute()
const { $infoBox, $access } = getCurrentInstance()!.appContext.config.globalProperties

/** 定义全部组件 **/
const allApplyPage = {
  'list': { name: '列表', component: null },
  'activityStatistics': { name: '活动看板', component: ActivityStatistics },
  'atatisticalDashboard': { name: '统计看板', component: StatisticalDashboard },
  'activityCreateSelectActivityTemplate': { name: '选择活动模板', component: ActivityCreateSelectActivityTemplate },
  'activityCreateEntry':  { name: '创建活动', component: ActivityCreateEntry }
}

const gzThreeRef = ref()
const infoTableRef = ref()
const generateCodeRef = ref()  // 生成二维码弹窗实例
const exportListRef = ref()
const exportScoreListRef = ref()
const applyPageComponentRef = ref()

let tableColumns = reactive([
  { key: 'activityNo', title: '活动编号', dataIndex: 'activityNo', fixed: 'left', width: 250, minWidth: 250, maxWidth: 300, },
  { key: 'activityName', title: '活动名称', dataIndex: 'activityName', width: 250, minWidth: 250, maxWidth: 300, },
  { key: 'activityImg', title: '活动海报', dataIndex: 'activityImg', width: 140, minWidth: 140, maxWidth: 170, },
  { key: 'exposureTime', title: '活动提前曝光时间', dataIndex: 'exposureTime', width: 170, minWidth: 170, maxWidth: 200, },
  { key: 'startTime', title: '活动开始时间', dataIndex: 'startTime', width: 170, minWidth: 170, maxWidth: 200, },
  { key: 'endTime', title: '活动结束时间', dataIndex: 'endTime', width: 170, minWidth: 170, maxWidth: 200, },
  { key: 'activityTypeName', title: '活动类型', dataIndex: 'activityTypeName', width: 140, minWidth: 140, maxWidth: 170, },
  { key: 'state', title: '活动状态', dataIndex: 'state', width: 140, minWidth: 140, maxWidth: 170, },
  { key: 'agentNo', title: '机构号', dataIndex: 'agentNo', width: 140, minWidth: 140, maxWidth: 170, },
  { key: 'agentName', title: '归属机构', dataIndex: 'agentName', width: 140, minWidth: 140, maxWidth: 170, },
  { key: 'operation', title: '操作', dataIndex: 'operation', width: 260, fixed: 'right', align: 'center', },
])

// 活动模板相关数据
const activityTemplate: any = ref([])
// 请求活动模板数据
req.list(API_URL_ACTIVITY_TEMPLATE, { pageSize: 200 }).then((res) => {
  activityTemplate.value = res.records
})

const searchData = ref({})

const vdata: any = reactive({
  currentApplyPage: allApplyPage.list, // 当前的步骤组件  null表示列表页
  activityDetail: {}, // 活动详情数据
  activityTemplateData: {}, // 创建活动的模板数据
})

// 向所有子组件注入参数 (子组件可直接更改此值)
provide('activityTemplateData', computed( ()=> vdata.activityTemplateData) )
// 向子组件传递出资方列表数据
provide('payAuthList', computed( ()=> payAuthList.value) )


// 导出领奖列表
function exportTable(activityId,activityName) {
  $exportExcel(API_URL_EXPORT_ACTIVITY_AWARD, { activityId }, 'POST').then(res => {
    fileDownload(res.data, `${activityName}.xlsx`)
  })
}
const activityTemplateCode  = ref()  as any
// 请求table接口数据
function reqTableDataFunc(params: any) { 
     if (route.path.includes('/activity/get')) {
      params.activityTemplateNo = 'ACTE004'
      activityTemplateCode.value = 'ACTE004'
    } else if (route.path.includes('/activity/issue')) {
      params.activityTemplateNo = 'ACTE006'
      activityTemplateCode.value = 'ACTE006'
    } else if (route.path.includes('/activity/other')) {
      activityTemplateCode.value = null
      params.activityTemplateNo = null     
    }
  // 获取当前页面的路由  
  return $activityList(params)
}

function searchFunc() {
  infoTableRef.value.refTable(true)
}
function searchFuncFlase() {
  infoTableRef.value.refTable()
}
/**
 * 获取出资方列表
 */
const payAuthList = ref([])
function getPayAuthList() {
  $getContributorList({}).then((result) => {
    payAuthList.value = result
  })
}
getPayAuthList()
/**
 * 活动统计看板 相关函数  -------------------------------
 */
function onStatistics(record) {
  vdata.activityDetail = record
  // 展示活动统计看板
  switchApplyPage({ page: 'activityStatistics', params: { activityDetail: record } })
}

// 统计看板
function onStatistical(record) {
  vdata.activityDetail = record
  // 展示统计看板
  switchApplyPage({ page: 'atatisticalDashboard', params: { activityDetail: record } })
}
/**
 * 切换面板
 * @param args { page: string, params: object }
 */
function switchApplyPage(args) {
  const { page, params } = args
  
  vdata.backupApplyPage = vdata.currentApplyPage
  vdata.currentApplyPage = allApplyPage[page]
  if(vdata.currentApplyPage && vdata.currentApplyPage.component){
    nextTick(() => { applyPageComponentRef.value.pageRender(params) })
  }else{
    //列表页
    infoTableRef.value.refTable(params?.refresh) // 刷新
  }
}
/**
 * 修改
 */
function activityEdit(record, isDetail = false) {
  // 修改活动 跳转到修改页面
  switchApplyPage({ page: 'activityCreateEntry', params: { isAdd: false, activityDetail: record, isDetail } })
}
// 删除活动
function activityDelete(record) {
  $infoBox.confirmDanger('确认删除？', '请确认是否删除当前活动？', () => {
    if (record.state !== 0) {
      $infoBox.message.warn('该活动非草稿状态，不能被删除！')
      return
    }
    $activityDelete(record.activityId, record.activityTemplateNo).then(
      (res) => {
        $infoBox.message.success('删除成功！')
        infoTableRef.value.refTable()
      }
    )
  })
}
// 活动上下线
function activityState(state, activityId) {
  let message = state === 4 ? '上线' : '下线'
  $infoBox.confirmDanger(
    `确认${message}？`,
    `请确认是否${message}当前活动？`,
    () => {
      $activityState({ state, activityId }).then(() => {
        $infoBox.message.success(`${message}成功！`)
        infoTableRef.value.refTable()
      })
    }
  )
}

// 获取活动类型信息
const activityType = ref([])
req.list(API_URL_ACTIVITY_TYPE, '').then((res) => {
  activityType.value = res.records 
})
// 获取商圈数据
const groupList = ref([])
// req.list(API_URL_MARKETINGGROUP, '').then((res) => {
//   groupList.value = res.records
// })

/**
 * 导出券码
 */
/**
 * 导出券码
 */
const onQrcodeExport = (activityId,record) => {
  $exportZip('/api/qrcodeRecord/getQrcodeRecordAllByActivityId',{activityId}).then(res=>{    
      const blob = new Blob([res.data], { type: 'application/zip' })
      // 创建下载链接
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = record.activityName + '.zip'
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      URL.revokeObjectURL(url)
  }).catch(error => {
  console.error('Error:', error)
})
}

// 撤回审核
const withdrawReview = (record) => {
  $infoBox.confirm(
    '确认撤回审核？',
    '请确认是否撤回当前活动的审核？',
    () => {
      $withdrawReview({ activityId: record.activityId }).then(() => {
        $infoBox.message.success('撤回审核成功！')
        infoTableRef.value.refTable()
      })
    }
  )
}
// 监听路由变化，使用watch
watch(() => route.fullPath, () => {
  // 当路由变化时，重置当前页面组件
  vdata.currentApplyPage = allApplyPage.list
  // 清空搜索条件
  searchData.value = {}
  // 刷新表格数据
  nextTick(() => {
    infoTableRef.value.refTable(true)
  })
})


</script>
<style lang="less" scoped>
:deep(.ant-image .ant-image-img) {
  width: 80px;
  height: 80px;
  object-fit: cover;
}

.opera {
  width: 100%;
  box-sizing: border-box;

  .content {
    display: flex;
    justify-content: space-between;

    .item {
      padding: 4px 4px !important;
    }

  }
}
</style>
